<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        :closable="false"
        show-icon>
      </el-alert>

      <!-- 选择商品分类 -->
      <el-row class="cat_opt">
        <el-col>
          <div class="selected">
            <span>选择商品分类：</span>
            <!-- 级联选择框 -->
            <el-cascader
              v-model="selectedCatKeys"
              :options="catelist"
              :props="cateProps"
              @change="handleChange"></el-cascader>
          </div>
        </el-col>
      </el-row>

      <!-- tabs 页签区域 -->
      <el-tabs v-model="activeName" @tab-click="tabsClick">
        <!-- 添加动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isThree" @click="addDataVisibile = true">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template v-slot="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag v-for="(item, index) in scope.row.attr_vals" :key="index" closable @close="handleClose(index, scope.row)">{{item}}</el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="el-tag-input"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加的按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot='scope'>
                <el-button size="mini" type="primary" @click="editParams(scope.row.attr_id)">编辑</el-button>
                <el-button size="mini" type="danger" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态树形 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isThree" @click="addDataVisibile = true">添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template v-slot="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag v-for="(item, index) in scope.row.attr_vals" :key="index" closable @close="handleClose(index, scope.row)">{{item}}</el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="el-tag-input"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加的按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot='scope'>
                <el-button size="mini" type="primary" @click="editParams(scope.row.attr_id)">编辑</el-button>
                <el-button size="mini" type="danger" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 添加动态参数、静态属性的对话框 -->
      <el-dialog
        :title="'添加' + titleText"
        :visible.sync="addDataVisibile"
        width="50%"
        @close="addDataClose('addDataRef')">
        <el-form ref="addDataRef" :model="addData" :rules="addDataRules" label-width="100px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addData.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="addDataVisibile = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改参数对话框 -->
      <el-dialog
        :title="'修改' + titleText"
        :visible.sync="editDataVisibile"
        width="50%"
        @close="addDataClose('editDataRef')">
        <el-form ref="editDataRef" :model="editData" :rules="editDataRules" label-width="100px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editData.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="editDataVisibile = false">取 消</el-button>
          <el-button type="primary" @click="editCommit">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类列表
      catelist: [],
      // 级联选择框的配置对象
      cateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 保存级联选择框选中的id
      selectedCatKeys: [],
      // 默认选中的页签名称
      activeName: 'many',
      // 动态参数列表
      manyTableData: [],
      // 静态属性列表
      onlyTableData: [],
      // 控制对话框是否显示
      addDataVisibile: false,
      // 添加参数的表单数据
      addData: {
        attr_name: ''
      },
      addDataRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      },
      // 控制对话框是否显示
      editDataVisibile: false,
      // 添加参数的表单数据
      editData: {},
      editDataRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取所有的商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败！')
      }
      this.catelist = res.data
    },
    // 级联选择框变化出发
    async handleChange() {
      this.getParamsData()
    },
    // 点击tabs标签
    tabsClick() {
      console.log(this.activeName)
      this.getParamsData()
    },
    // 抽离出公共方法  参数列表  获取数据
    async getParamsData() {
      if (this.selectedCatKeys.length !== 3) {
        // 证明选中的不是三级分类
        this.selectedCatKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return false
      }
      // 证明选中的是三级分类
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: this.activeName
        }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品参数失败！')
      }
      // 将tag要显示的字符串转换成数组，用于循环
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 因为循环出来的输入框会产生联动效果，因此为每个tag单独添加一个属性
        item.inputVisible = false
        item.inputValue = ''
      })
      console.log(res.data)
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 抽离出公共方法  tags列表  获取数据
    async saveAttrValue(row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        return this.$message.error('新增商品信息失败！')
      }
      this.$message.success('新增商品信息成功！')
    },
    // 关闭对话框
    addDataClose(refName) {
      this.$refs[refName].resetFields()
    },
    // 点击按钮添加参数
    addParams() {
      this.$refs.addDataRef.validate(async valid => {
        if (!valid) {
          return false
        }
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addData.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) {
          return this.$message.error('创建参数失败！')
        }
        this.$message.success('创建参数成功！')
        this.getParamsData()
        this.addDataVisibile = false
      })
    },
    // 修改参数
    async editParams(attrId) {
      // 查询当前参数的信息
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attrId}`, {
        params: {
          attr_sel: this.activeName
        }
      })
      if (res.meta.status !== 200) {
        this.$message.error('获取用户信息失败！')
      }
      this.editData = res.data
      // console.log(this.editData)
      this.editDataVisibile = true
    },
    // 确定编辑修改信息
    editCommit() {
      this.$refs.editDataRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editData.attr_id}`, {
          attr_name: this.editData.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) {
          this.$message.error('修改信息失败！')
        }
        this.getParamsData()
        this.$message.success('修改信息成功！')
        this.editDataVisibile = false
      })
    },
    // 根据id删除对应的id项
    async removeParams(attrId) {
      const confirmResult = await this.$confirm('确定删除该参数吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${attrId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败！')
      }
      this.$message.success('删除参数成功！')
      this.getParamsData()
    },
    // 文本框失去焦点或者按下了enter触发函数
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return false
      }
      // 如果没有return，则说明用户输入了有用的内容，需要处理
      row.attr_vals.push(row.inputValue.trim())
      this.saveAttrValue(row)
      row.inputValue = ''
      row.inputVisible = false
    },
    // 点击按钮显示文本输入框
    showInput(date) {
      date.inputVisible = true
      // 在按钮渲染成输入框之后，才能执行代码
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除对应的tag参数
    handleClose(i, row) {
      // 这里用的方法是删除数组中的某一个数值，然后重新发送put请求
      row.attr_vals.splice(i, 1)
      this.saveAttrValue(row)
    }
  },
  computed: {
    isThree() {
      // 如果按钮需要禁用，返回true，反之返回false
      if (this.selectedCatKeys.length !== 3) {
        return true
      }
      return false
    },
    // 当前选中的三级分类的id，用于发送网络请求
    cateId() {
      if (this.selectedCatKeys.length !== 3) {
        return null
      }
      return this.selectedCatKeys[2]
    },
    // 对话框的名称
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.selected {
  display: flex;
  align-items: center;
  > span:nth-child(1) {
    padding-right: 15px;
  }
  .el-cascader {
    width: 200px;
  }
}
.el-tag {
  margin: 10px;
}
.el-tag-input {
  width: 150px;
}
</style>
